package com.example.demo.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** 
* @ClassName: PhoneMaskingUtil 
* @Description: TODO(这里用一句话描述这个类的作用) 
* @author majie
* @date 2024年12月24日  
*/
public class PhoneMaskingUtil {

    // 脱敏手机号的方法
    public static String desensitizePhoneNumber(String input) {
        // 匹配多种格式包含多余字符的手机号相关字符串的正则表达式
        String regexConfig = "[\\s-_*=^~#$+()/\\:'?,<>.]*";
        String regex = "(?<!\\d)(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})"+ regexConfig +"(\\d{1})(?!\\d)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            // 获取匹配到的手机号字符串
            String phoneNumber = matcher.group().replaceAll(regexConfig, "");
            String replacement = phoneNumber.substring(0, 3) + "****" + phoneNumber.substring(7);
            matcher.appendReplacement(result, replacement);
        }
        matcher.appendTail(result);
        return result.toString();
    }

    
    public static void main(String[] args) {
           String[] inputs = {
        		   "123456-789",
        		   "131 +_1951-4715fe",
        		   "131 1951 4715fe",
        		   "131 19514 715fe2",
        		   "13119-#$+55fe",
                   "13119514715xxxxfe",
                   "131-1951-4715df",
                   "13-11-951-47-15df,1311591471",
                   "13-11-951-4715df2",
                   "131--1951--4715re",
                   "131*1951*4715",
                   "131**1951**4715",
                   "131=1951=4715",
                   "131*1951*4715sdf",
                   "13119514715fe",
                   "13-1195-147-15dfxxs,13-1195-147-15df",
                   "1-311-95147-15re1",
                   "1-311-95147-1-5re1",
                   "131*1951*4715sdf"
           };
           for (String input : inputs) {
               System.out.println(desensitizePhoneNumber(input));
           }
    }
    
}
